package com.eagle.roomsearch.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

/**
 * Redis的Value序列化与反序列化
 *
 * @author Jetvin
 * @date 2018/3/1
 * @time 16:55
 */
public class RedisSerializerConfig implements RedisSerializer<Object> {

    private Charset charset;

    public RedisSerializerConfig() {

        this(Charset.forName("UTF8"));
    }

    public RedisSerializerConfig(Charset charset) {

        this.charset = charset;
    }

    @Override
    public byte[] serialize(Object o) throws SerializationException {

        String json = JSONObject.toJSONString(o, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteEnumUsingToString);
        System.out.println(">>>>>" + json);

        return json.getBytes(charset);
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {

        if (bytes == null) {
            return null;
        }
        //list的話會有異常
        String json = new String(bytes, charset);
        System.out.println("<<<<<" + json);

        return JSON.parseObject(json);
    }
}
